import { DeviceStorage } from "./DeviceStorage";
import { DeviceEventEmitter } from 'react-native'
import { SOCKET_URL } from "../config";

export async function messageListener() {
    const jwt = await DeviceStorage.get('jwt')
    if (!jwt) return
    const ws = new WebSocket(`${SOCKET_URL}/message?jwt=${jwt}`)
    ws.onopen = () => {
        // 打开一个连接
    };

    ws.onmessage = (e) => {
        if (e.data) {
            console.log('new socket: ', e.data);
            DeviceEventEmitter.emit('newMessage')
        }
    };

    ws.onerror = (e) => {
        // 发生了一个错误
        console.log(e.message);
    };

    ws.onclose = (e) => {
        // 连接被关闭了
        console.log(e.code, e.reason);
    };
}
